package cn.dapeng.ticket;


import cn.dapeng.util.SleepingUtil;

import java.util.concurrent.TimeUnit;

/**
 * 这个例子，如果不让线程睡眠一段时间， 很难看到不同步的情况
 */

public class Ticket_Demo01 {

    public int tickets = 10000;

    public synchronized void sale() {
        tickets--;
        SleepingUtil.sleep(1, TimeUnit.MILLISECONDS);
        if (tickets == 0) {
            System.exit(0);
        }
        System.out.println(Thread.currentThread().getName() + ":" + tickets);
    }

    public synchronized int getTickets() {
        return tickets;
    }

    public static void main(String[] args) {
        Ticket_Demo01 demo01 = new Ticket_Demo01();

        new Thread(() -> {
            while (true) {
                demo01.sale();
            }
        }, "T1").start();

        new Thread(() -> {
            while (true) {
                demo01.sale();
            }
        }, "T2").start();
    }
}
